import type { MockMethod } from "vite-plugin-mock";

// 模拟订单数据
const orderList = [
  {
    id: 1,
    orderNo: "ORD20230801001",
    userId: 1001,
    userName: "张三",
    userPhone: "13800138001",
    userEmail: "zhangsan@example.com",
    totalAmount: 299.0,
    payAmount: 299.0,
    status: 3, // 待发货
    statusName: "待发货",
    paymentMethod: "微信支付",
    paymentTime: "2023-08-01T10:30:00Z",
    createTime: "2023-08-01T10:00:00Z",
    shipTime: null,
    completeTime: null,
    remark: "用户备注：请尽快发货",
    adminRemark: "",
    shippingAddress: {
      province: "浙江省",
      city: "杭州市",
      district: "西湖区",
      detail: "文三路138号",
      receiverName: "张三",
      receiverPhone: "13800138001"
    },
    logistics: {
      company: "",
      trackingNumber: "",
      status: ""
    },
    items: [
      {
        id: 1,
        productId: 101,
        productName: "iPhone 14 Pro",
        productImage: "/images/iphone14.jpg",
        sku: "IP14P-256-BLK",
        quantity: 1,
        unitPrice: 299.0,
        totalPrice: 299.0
      }
    ]
  },
  {
    id: 2,
    orderNo: "ORD20230801002",
    userId: 1002,
    userName: "李四",
    userPhone: "13800138002",
    userEmail: "lisi@example.com",
    totalAmount: 199.0,
    payAmount: 199.0,
    status: 4, // 已发货
    statusName: "已发货",
    paymentMethod: "支付宝",
    paymentTime: "2023-08-01T11:00:00Z",
    createTime: "2023-08-01T10:45:00Z",
    shipTime: "2023-08-01T14:00:00Z",
    completeTime: null,
    remark: "",
    adminRemark: "优先发货",
    shippingAddress: {
      province: "上海市",
      city: "上海市",
      district: "浦东新区",
      detail: "陆家嘴环路1000号",
      receiverName: "李四",
      receiverPhone: "13800138002"
    },
    logistics: {
      company: "顺丰速运",
      trackingNumber: "SF1234567890",
      status: "运输中"
    },
    items: [
      {
        id: 2,
        productId: 102,
        productName: "MacBook Air",
        productImage: "/images/macbook.jpg",
        sku: "MBA-M2-256-SLV",
        quantity: 1,
        unitPrice: 199.0,
        totalPrice: 199.0
      }
    ]
  },
  {
    id: 3,
    orderNo: "ORD20230801003",
    userId: 1003,
    userName: "王五",
    userPhone: "13800138003",
    userEmail: "wangwu@example.com",
    totalAmount: 89.0,
    payAmount: 89.0,
    status: 5, // 已完成
    statusName: "已完成",
    paymentMethod: "银行卡",
    paymentTime: "2023-07-30T09:00:00Z",
    createTime: "2023-07-30T08:30:00Z",
    shipTime: "2023-07-30T16:00:00Z",
    completeTime: "2023-08-01T10:00:00Z",
    remark: "用户备注：包装要仔细",
    adminRemark: "已按要求包装",
    shippingAddress: {
      province: "广东省",
      city: "深圳市",
      district: "南山区",
      detail: "科技园南区",
      receiverName: "王五",
      receiverPhone: "13800138003"
    },
    logistics: {
      company: "韵达快递",
      trackingNumber: "YD9876543210",
      status: "已签收"
    },
    items: [
      {
        id: 3,
        productId: 103,
        productName: "AirPods Pro",
        productImage: "/images/airpods.jpg",
        sku: "AP-PRO-WHT",
        quantity: 1,
        unitPrice: 89.0,
        totalPrice: 89.0
      }
    ]
  },
  {
    id: 4,
    orderNo: "ORD20230802001",
    userId: 1004,
    userName: "赵六",
    userPhone: "13800138004",
    userEmail: "zhaoliu@example.com",
    totalAmount: 1299.0,
    payAmount: 1299.0,
    status: 1, // 待付款
    statusName: "待付款",
    paymentMethod: "",
    paymentTime: null,
    createTime: "2023-08-02T09:15:00Z",
    shipTime: null,
    completeTime: null,
    remark: "",
    adminRemark: "",
    shippingAddress: {
      province: "北京市",
      city: "北京市",
      district: "朝阳区",
      detail: "三里屯SOHO",
      receiverName: "赵六",
      receiverPhone: "13800138004"
    },
    logistics: {
      company: "",
      trackingNumber: "",
      status: ""
    },
    items: [
      {
        id: 4,
        productId: 104,
        productName: "iPad Pro 12.9",
        productImage: "/images/ipad.jpg",
        sku: "IPP-129-512-GRY",
        quantity: 1,
        unitPrice: 1299.0,
        totalPrice: 1299.0
      }
    ]
  },
  {
    id: 5,
    orderNo: "ORD20230802002",
    userId: 1005,
    userName: "钱七",
    userPhone: "13800138005",
    userEmail: "qianqi@example.com",
    totalAmount: 599.0,
    payAmount: 599.0,
    status: 6, // 已取消
    statusName: "已取消",
    paymentMethod: "",
    paymentTime: null,
    createTime: "2023-08-02T14:20:00Z",
    shipTime: null,
    completeTime: null,
    remark: "用户要求取消",
    adminRemark: "用户主动取消",
    shippingAddress: {
      province: "江苏省",
      city: "南京市",
      district: "鼓楼区",
      detail: "中山路100号",
      receiverName: "钱七",
      receiverPhone: "13800138005"
    },
    logistics: {
      company: "",
      trackingNumber: "",
      status: ""
    },
    items: [
      {
        id: 5,
        productId: 105,
        productName: "Apple Watch Series 8",
        productImage: "/images/watch.jpg",
        sku: "AWS8-41-GPS-BLK",
        quantity: 1,
        unitPrice: 599.0,
        totalPrice: 599.0
      }
    ]
  }
];

// 模拟订单日志数据
const orderLogs = {
  1: [
    {
      id: 1,
      orderId: 1,
      operatorId: 1,
      operatorName: "系统",
      operationType: "CREATE",
      operationName: "创建订单",
      remark: "用户下单",
      createTime: "2023-08-01T10:00:00Z"
    },
    {
      id: 2,
      orderId: 1,
      operatorId: 1001,
      operatorName: "张三",
      operationType: "PAYMENT",
      operationName: "支付订单",
      remark: "微信支付完成",
      createTime: "2023-08-01T10:30:00Z"
    }
  ],
  2: [
    {
      id: 3,
      orderId: 2,
      operatorId: 1,
      operatorName: "系统",
      operationType: "CREATE",
      operationName: "创建订单",
      remark: "用户下单",
      createTime: "2023-08-01T10:45:00Z"
    },
    {
      id: 4,
      orderId: 2,
      operatorId: 1002,
      operatorName: "李四",
      operationType: "PAYMENT",
      operationName: "支付订单",
      remark: "支付宝支付完成",
      createTime: "2023-08-01T11:00:00Z"
    },
    {
      id: 5,
      orderId: 2,
      operatorId: 1,
      operatorName: "管理员",
      operationType: "SHIP",
      operationName: "订单发货",
      remark: "顺丰速运 SF1234567890",
      createTime: "2023-08-01T14:00:00Z"
    }
  ]
};

// 订单状态映射
const statusMap = {
  1: "待付款",
  2: "已付款",
  3: "待发货",
  4: "已发货",
  5: "已完成",
  6: "已取消"
};

export default [
  // 获取订单列表
  {
    url: "/order-management/orders",
    method: "get",
    response: ({ query }) => {
      let filteredOrders = [...orderList];

      // 筛选条件
      if (query.status && query.status !== "0") {
        filteredOrders = filteredOrders.filter(order => order.status === parseInt(query.status));
      }

      if (query.orderNo) {
        filteredOrders = filteredOrders.filter(order =>
          order.orderNo.toLowerCase().includes(query.orderNo.toLowerCase())
        );
      }

      if (query.userId) {
        filteredOrders = filteredOrders.filter(order => order.userId.toString().includes(query.userId));
      }

      if (query.userName) {
        filteredOrders = filteredOrders.filter(order => order.userName.includes(query.userName));
      }

      if (query.startTime && query.endTime) {
        filteredOrders = filteredOrders.filter(
          order => order.createTime >= query.startTime && order.createTime <= query.endTime
        );
      }

      // 排序
      if (query.sortBy) {
        filteredOrders.sort((a, b) => {
          const direction = query.sortOrder === "desc" ? -1 : 1;
          switch (query.sortBy) {
            case "createTime":
              return direction * (new Date(a.createTime).getTime() - new Date(b.createTime).getTime());
            case "paymentTime":
              return (
                direction * (new Date(a.paymentTime || 0).getTime() - new Date(b.paymentTime || 0).getTime())
              );
            case "totalAmount":
              return direction * (a.totalAmount - b.totalAmount);
            default:
              return 0;
          }
        });
      }

      // 分页
      const page = parseInt(query.page) || 1;
      const pageSize = parseInt(query.pageSize) || 10;
      const start = (page - 1) * pageSize;
      const end = start + pageSize;

      return {
        code: 200,
        message: "success",
        rows: filteredOrders.slice(start, end),
        total: filteredOrders.length
      };
    }
  },

  // 获取订单详情
  {
    url: "/order-management/orders/:id",
    method: "get",
    response: ({ query }) => {
      const orderId = parseInt(query.id);
      const order = orderList.find(o => o.id === orderId);

      if (!order) {
        return {
          code: 404,
          message: "订单不存在"
        };
      }

      return {
        code: 200,
        message: "success",
        data: order
      };
    }
  },

  // 更新订单状态
  {
    url: "/order-management/orders/:id/status",
    method: "put",
    response: ({ query, body }) => {
      const orderId = parseInt(query.id);
      const { status, remark } = body;
      const orderIndex = orderList.findIndex(o => o.id === orderId);

      if (orderIndex === -1) {
        return {
          code: 404,
          message: "订单不存在"
        };
      }

      orderList[orderIndex].status = status;
      orderList[orderIndex].statusName = statusMap[status];
      if (remark) {
        orderList[orderIndex].adminRemark = remark;
      }

      // 更新相关时间
      const now = new Date().toISOString();
      if (status === 4) {
        // 已发货
        orderList[orderIndex].shipTime = now;
      } else if (status === 5) {
        // 已完成
        orderList[orderIndex].completeTime = now;
      }

      return {
        code: 200,
        message: "订单状态更新成功"
      };
    }
  },

  // 批量更新订单状态
  {
    url: "/order-management/orders/batch-status",
    method: "put",
    response: ({ body }) => {
      const { orderIds, status, remark } = body;

      orderIds.forEach(orderId => {
        const orderIndex = orderList.findIndex(o => o.id === orderId);
        if (orderIndex !== -1) {
          orderList[orderIndex].status = status;
          orderList[orderIndex].statusName = statusMap[status];
          if (remark) {
            orderList[orderIndex].adminRemark = remark;
          }

          const now = new Date().toISOString();
          if (status === 4) {
            orderList[orderIndex].shipTime = now;
          } else if (status === 5) {
            orderList[orderIndex].completeTime = now;
          }
        }
      });

      return {
        code: 200,
        message: "批量更新成功"
      };
    }
  },

  // 更新订单备注
  {
    url: "/order-management/orders/:id/remark",
    method: "put",
    response: ({ query, body }) => {
      const orderId = parseInt(query.id);
      const { remark } = body;
      const orderIndex = orderList.findIndex(o => o.id === orderId);

      if (orderIndex === -1) {
        return {
          code: 404,
          message: "订单不存在"
        };
      }

      orderList[orderIndex].adminRemark = remark;

      return {
        code: 200,
        message: "备注更新成功"
      };
    }
  },

  // 订单发货
  {
    url: "/order-management/orders/:id/ship",
    method: "post",
    response: ({ query, body }) => {
      const orderId = parseInt(query.id);
      const { logisticsCompany, trackingNumber, remark } = body;
      const orderIndex = orderList.findIndex(o => o.id === orderId);

      if (orderIndex === -1) {
        return {
          code: 404,
          message: "订单不存在"
        };
      }

      orderList[orderIndex].status = 4; // 已发货
      orderList[orderIndex].statusName = "已发货";
      orderList[orderIndex].shipTime = new Date().toISOString();
      orderList[orderIndex].logistics.company = logisticsCompany;
      orderList[orderIndex].logistics.trackingNumber = trackingNumber;
      orderList[orderIndex].logistics.status = "运输中";

      if (remark) {
        orderList[orderIndex].adminRemark = remark;
      }

      return {
        code: 200,
        message: "发货成功"
      };
    }
  },

  // 批量发货
  {
    url: "/order-management/orders/batch-ship",
    method: "post",
    response: ({ body }) => {
      const { orders } = body;

      orders.forEach(shipInfo => {
        const orderIndex = orderList.findIndex(o => o.id === shipInfo.orderId);
        if (orderIndex !== -1) {
          orderList[orderIndex].status = 4;
          orderList[orderIndex].statusName = "已发货";
          orderList[orderIndex].shipTime = new Date().toISOString();
          orderList[orderIndex].logistics.company = shipInfo.logisticsCompany;
          orderList[orderIndex].logistics.trackingNumber = shipInfo.trackingNumber;
          orderList[orderIndex].logistics.status = "运输中";

          if (shipInfo.remark) {
            orderList[orderIndex].adminRemark = shipInfo.remark;
          }
        }
      });

      return {
        code: 200,
        message: "批量发货成功"
      };
    }
  },

  // 获取订单日志
  {
    url: "/order-management/orders/:id/logs",
    method: "get",
    response: ({ query }) => {
      const orderId = parseInt(query.id);
      const logs = orderLogs[orderId] || [];

      return {
        code: 200,
        message: "success",
        data: logs
      };
    }
  },

  // 导出订单
  {
    url: "/order-management/orders/export",
    method: "get",
    response: () => {
      // 模拟导出，实际应该返回文件流
      return {
        code: 200,
        message: "导出成功",
        data: {
          downloadUrl: "/download/orders_export.xlsx"
        }
      };
    }
  },

  // 获取订单统计
  {
    url: "/order-management/orders/statistics",
    method: "get",
    response: () => {
      const stats = {
        totalOrders: orderList.length,
        pendingPayment: orderList.filter(o => o.status === 1).length,
        paid: orderList.filter(o => o.status === 2).length,
        pendingShipment: orderList.filter(o => o.status === 3).length,
        shipped: orderList.filter(o => o.status === 4).length,
        completed: orderList.filter(o => o.status === 5).length,
        cancelled: orderList.filter(o => o.status === 6).length,
        totalAmount: orderList.reduce((sum, order) => sum + order.totalAmount, 0),
        paidAmount: orderList
          .filter(o => o.status >= 2 && o.status !== 6)
          .reduce((sum, order) => sum + order.payAmount, 0)
      };

      return {
        code: 200,
        message: "success",
        data: stats
      };
    }
  },

  // 取消订单
  {
    url: "/order-management/orders/:id/cancel",
    method: "post",
    response: ({ query, body }) => {
      const orderId = parseInt(query.id);
      const { reason } = body;
      const orderIndex = orderList.findIndex(o => o.id === orderId);

      if (orderIndex === -1) {
        return {
          code: 404,
          message: "订单不存在"
        };
      }

      orderList[orderIndex].status = 6; // 已取消
      orderList[orderIndex].statusName = "已取消";
      orderList[orderIndex].adminRemark = reason || "订单已取消";

      return {
        code: 200,
        message: "订单取消成功"
      };
    }
  },

  // 获取物流信息
  {
    url: "/order-management/orders/:id/logistics",
    method: "get",
    response: ({ query }) => {
      const orderId = parseInt(query.id);
      const order = orderList.find(o => o.id === orderId);

      if (!order) {
        return {
          code: 404,
          message: "订单不存在"
        };
      }

      // 模拟物流轨迹
      const mockLogistics = {
        company: order.logistics.company,
        trackingNumber: order.logistics.trackingNumber,
        status: order.logistics.status,
        tracks: order.logistics.trackingNumber
          ? [
              {
                time: "2023-08-01T14:00:00Z",
                status: "已发货",
                description: "商品已从仓库发出"
              },
              {
                time: "2023-08-01T18:00:00Z",
                status: "运输中",
                description: "快件已到达中转站"
              },
              {
                time: "2023-08-02T08:00:00Z",
                status: "派送中",
                description: "快件正在派送途中"
              }
            ]
          : []
      };

      return {
        code: 200,
        message: "success",
        data: mockLogistics
      };
    }
  }
] as MockMethod[];
